//
//  PayTicketViewController.m
//  didacar
//
//  Created by 度周末网络-王腾 on 15/12/23.
//  Copyright © 2015年 dzmmac. All rights reserved.
//

#import "PayTicketViewController.h"
#import "PayTicketHeaderTableCell.h"
#import "PayTicketDescTableCell.h"
#import "PayTicketPayTypeTableCell.h"
#import "TicketViewController.h"
#import "PaySuccessViewController.h"
#import "CalendarDayModel.h"
#import "WXApi.h"
#import "WXApiManager.h"
#import "PayViewModel.h"
#import "AlipayManager.h"
@interface PayTicketViewController () <PayTicketDescDelegate,SelectedTickedDelegate,WXApiManagerDelegate,AlipayManagerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *mainTable;
- (IBAction)payAction:(UIButton *)sender;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottom_top_line;

@property (nonatomic , strong) PayViewModel *payViewModel;


@property (strong, nonatomic) IBOutlet UIButton *payBtn;

@end

@implementation PayTicketViewController


-(void)awakeFromNib{
     self.payViewModel = [[PayViewModel alloc ] init];
     self.payTicketViewModel = [[PayTicketViewModel alloc ] init];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setLeftBtnItem];
    
    [WXApiManager sharedManager].delegate = self;
    [AlipayManager sharedManager].delegate = self;
    
    self.tmpTotalDayPrice = self.totalDayPrice;
    
    self.navigationItem.title = @"支付";
    self.bottom_top_line.constant = 0.45;
    
    [self setExtraCellLineHidden:self.mainTable];
    
    
    switch (self.payTicketStyle) {
        case PayTicket_Day:
        {
            self.payTicketViewModel.requestPayTicketModel.MemberId = USERINFOManager.getUserInfo.MemberId;
            self.payTicketViewModel.requestPayTicketModel.LineId   = self.entity.LineId;
            self.payTicketViewModel.requestPayTicketModel.StartStationId=self.entity.StartStationId;
            self.payTicketViewModel.requestPayTicketModel.EndStationId  = self.entity.EndStationId;
            self.payTicketViewModel.requestPayTicketModel.PayType = 1;
            self.payTicketViewModel.requestPayTicketModel.PiaoJId  = self.entity.PiaoJId;
            
            NSMutableArray *postDayTicket = [[NSMutableArray alloc ] init];
            for (CalendarDayModel *dayModel in self.dayTickets) {
                TicketDateDetail *dateDetail = [[TicketDateDetail alloc ] init];
                dateDetail.BcId        = dayModel.BCID;
                dateDetail.TicketPrice = [NSDecimalNumber decimalNumberWithString:dayModel.price];
                dateDetail.SalePrice   = dayModel.SalePrice;
                dateDetail.SendTime    = self.entity.SendTime;
                [postDayTicket addObject:dateDetail];;
            }
            self.payTicketViewModel.requestPayTicketModel.ticketdateList = postDayTicket;
          
        }
            break;
            
        case PayTicket_Month:{
            self.payTicketViewModel.requestPayTicketModel.MemberId = USERINFOManager.getUserInfo.MemberId;
            self.payTicketViewModel.requestPayTicketModel.LineId   = self.entity.LineId;
            self.payTicketViewModel.requestPayTicketModel.StartStationId=self.entity.StartStationId;
            self.payTicketViewModel.requestPayTicketModel.EndStationId  = self.entity.EndStationId;
            self.payTicketViewModel.requestPayTicketModel.PayType = 1;
            self.payTicketViewModel.requestPayTicketModel.PiaoJId  = self.entity.PiaoJId;
            self.payTicketViewModel.requestPayTicketModel.TicketMonth = self.entity.TicketMonth;
            self.payTicketViewModel.requestPayTicketModel.BCID  = self.entity.BCID;
            self.payTicketViewModel.requestPayTicketModel.SendTime = self.entity.SendTime;
        }
            break;
        case PayTicket_ThroughBus:{
            self.payTicketViewModel.requestPayTicketModel.MemberId = USERINFOManager.getUserInfo.MemberId;
            self.payTicketViewModel.requestPayTicketModel.LineId   = self.entity.LineId;
            self.payTicketViewModel.requestPayTicketModel.StartStationId=self.entity.StartStationId;
            self.payTicketViewModel.requestPayTicketModel.EndStationId  = self.entity.EndStationId;
            self.payTicketViewModel.requestPayTicketModel.PayType = 1;
            self.payTicketViewModel.requestPayTicketModel.PiaoJId  = self.entity.PiaoJId;
            self.payTicketViewModel.requestPayTicketModel.BCID  = self.entity.BCID;
            self.payTicketViewModel.requestPayTicketModel.TicketTime = self.entity.TicketTime;
            self.payTicketViewModel.requestPayTicketModel.SendTime = self.entity.SendTime;
            self.payTicketViewModel.requestPayTicketModel.TicketPrice = self.entity.TicketPrice;
            self.payTicketViewModel.requestPayTicketModel.SalePrice = self.entity.SalePrice;
            
        }
            break;
        default:
            break;
    }
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 80;
    }else if (indexPath.section == 1) {
        return 132;
    }else{
        return 44;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.01;
    }
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        UIView *sectionView = [[UIView alloc ] initWithFrame:CGRectMake(0, 0, [UIScreen width], 0.01)];
        return sectionView;
    }
    UIView *sectionView = [[UIView alloc ] initWithFrame:CGRectMake(0, 0, [UIScreen width], 40)];
    UILabel *textLabel = [[UILabel alloc ] initWithFrame:CGRectMake(14, 0, [UIScreen width] - 28, 40)];
    textLabel.textColor = [UIColor darkGrayColor];
    textLabel.font = [UIFont systemFontOfSize:13];
    [sectionView addSubview:textLabel];
    
    if (section == 1) {
        textLabel.text = @"购票详情";
    }else{
        textLabel.text = @"支付方式";
    }
    return sectionView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0 || section == 1) {
        return 1;
    }else{
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        PayTicketHeaderTableCell *headerCell = [tableView dequeueReusableCellWithIdentifier:@"PayTicketHeaderTableCell"];
//        [headerCell setCellPayTicketStyle:self.payTicketStyle];
        [headerCell showEntity:self.entity];
        return headerCell;
    }else if (indexPath.section == 1){
        PayTicketDescTableCell *descCell = [tableView dequeueReusableCellWithIdentifier:@"PayTicketDescTableCell"];
        descCell.delegate = self;
        
        
        descCell.countLabel.text = @(self.payTicketViewModel.ticketCount).stringValue;
        
        
        if (self.payTicketViewModel.discountPrice == 0) {
            // 优惠价格
            descCell.discountPrice.text = @"0元";
        }else{
            // 优惠价格
            descCell.discountPrice.text = [NSString stringWithFormat:@"-%@元",@(self.payTicketViewModel.discountPrice).stringValue];
        }
     
        
        [descCell setCellPayTicketStyle:self.payTicketStyle dayCount:self.totalDay];
        descCell.totalPrice.text = [NSString stringWithFormat:@"%@元",self.totalDayPrice];
        
        return descCell;
    }else{
        PayTicketPayTypeTableCell *payTypeCell = [tableView dequeueReusableCellWithIdentifier:@"PayTicketPayTypeTableCell"];
        payTypeCell.indexPath = indexPath;
        [payTypeCell selectedPayType:self.payTicketViewModel.selectedPayType];
        return payTypeCell;
    }
}

- (void)addBtnAction:(UIButton *)sender{
    self.payTicketViewModel.ticketCount ++;
    
    [self calculatePrice];
 
    
    [self.mainTable reloadData];
}

- (void)mintueBtnAction:(UIButton *)sender{
    
    if (self.payTicketViewModel.ticketCount==1) {
        return;
    }
    self.payTicketViewModel.ticketCount --;
    
    [self calculatePrice];
    
    [self.mainTable reloadData];
}

-(void)calculatePrice{
    
    self.totalDayPrice = [NSString stringWithFormat:@"%@",@([self.tmpTotalDayPrice integerValue]*self.payTicketViewModel.ticketCount ).stringValue];
}

- (void)selectedSaleTicketBtnAction:(UIButton *)sender{
    TicketViewController *ticket = [[UIStoryboard storyboardWithName:@"MyTicket" bundle:nil]  instantiateViewControllerWithIdentifier:@"TicketViewController"];
    ticket.isSelect = YES;
    ticket.delegate = self;
    
    if (self.payTicketStyle == PayTicket_ThroughBus) {
        ticket.LineType = 2;
    }else{
        ticket.LineType = 1;
    }
    ticket.SendTime =  self.entity.SendTime;
    ticket.OrderAmount = [NSDecimalNumber decimalNumberWithString:self.totalDayPrice];
    
    [self.navigationController pushViewController:ticket animated:YES];
}

-(void)selectedTicket:(CouponEntity *)model{
    
    if (model == nil) {
        self.payTicketViewModel.discountPrice = 0;
        self.payTicketViewModel.requestPayTicketModel.DjqId = 0;
    }else{
        self.payTicketViewModel.discountPrice = [model.Amount floatValue];
        self.payTicketViewModel.requestPayTicketModel.DjqId = model.CouponsMId;
    }
    
    [self.mainTable reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2) {
        self.payTicketViewModel.selectedPayType = indexPath.row;
        
        self.payTicketViewModel.requestPayTicketModel.PayType = self.payTicketViewModel.selectedPayType + 1;
        [self.mainTable reloadData];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)payAction:(UIButton *)sender {
    
    switch (self.payTicketStyle) {
        case PayTicket_Day:
        {
            [self.payTicketViewModel dayTicketOrder:^(NSInteger resultType, id data, NSString *errorMsg) {
                WEAKSELF
                if (resultType == 1) {
                    [weakSelf getOrderNumberSuccess];
                }else{
                    [SVProgressHUD showErrorWithStatus:errorMsg];
                }
                
            }];
        }
            break;
        case PayTicket_Month:{
            
            
            WEAKSELF
            [self.payTicketViewModel monthTicketOrder:^(NSInteger resultType, id data, NSString *errorMsg) {
                
                if (resultType == 1) {
                    [weakSelf getOrderNumberSuccess];
                }else{
                    [SVProgressHUD showErrorWithStatus:errorMsg];
                }
            }];
        }
            break;
            
        case PayTicket_ThroughBus:{
            self.payTicketViewModel.requestPayTicketModel.TicketNum = @(self.payTicketViewModel.ticketCount).stringValue;
            
            self.payTicketViewModel.requestPayTicketModel.TicketPrice = [NSDecimalNumber decimalNumberWithString:self.totalDayPrice];
            self.payTicketViewModel.requestPayTicketModel.SalePrice = [NSDecimalNumber decimalNumberWithString:@([self.entity.SalePrice floatValue]*self.payTicketViewModel.ticketCount).stringValue];
            
            WEAKSELF
            [self.payTicketViewModel throughBusOrder:^(NSInteger resultType, id data, NSString *errorMsg) {
                
                if (resultType == 1) {
                    [weakSelf getOrderNumberSuccess];
                }else{
                    [SVProgressHUD showErrorWithStatus:errorMsg];
                }
            }];
        }
            break;
        default:
            break;
    }
}

-(void)wxPayRespSuccess{
    [self paySuccess];
}

-(void)wxPayRespError{
    
}

-(void)alipayPayRespSuccess{
     [self paySuccess];
}


-(void)alipayPayRespError{
    
}

-(void)getOrderNumberSuccess{
    self.payViewModel.PayChannel = self.payTicketViewModel.selectedPayType +1;
    self.payViewModel.OrderNumber = self.payTicketViewModel.TicketOrderNum;
    
    WEAKSELF
    [self.payViewModel getPayMsg:^(NSInteger resultType, id data, NSString *errorMsg) {
        
        
        if (resultType == 1) {
            NSInteger status = [[weakSelf.payViewModel.responseDic objectForKey:@"PayStatus"] integerValue];
            //代表已支付
            if (status == 3) {
                [weakSelf paySuccess];
            }else if (status == 1 && [weakSelf.payViewModel.responseDic objectForKey:@"PayInfo"]!= nil){
                
                if (weakSelf.payViewModel.PayChannel == 1) {
                    [[AlipayManager sharedManager] alipaySdk:[weakSelf.payViewModel.responseDic objectForKey:@"PayInfo"]];
                }else{
                    
                    [[WXApiManager sharedManager] wxPaySdk:[weakSelf.payViewModel.responseDic objectForKey:@"PayInfo"]];
                }
                
            }else{
                [SVProgressHUD showErrorWithStatus:errorMsg];
            }
        }else{
          [SVProgressHUD showErrorWithStatus:errorMsg];
        }
    }];
}

-(void)paySuccess{
    PaySuccessViewController *paySuccess = [[UIStoryboard storyboardWithName:@"Ticket" bundle:nil]  instantiateViewControllerWithIdentifier:@"PaySuccessViewController"];
    [self calculatePrice];
    paySuccess.price = self.totalDayPrice;
    [self.navigationController pushViewController:paySuccess animated:YES];
}

@end
